package util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@ConfigurationProperties("jwt.config")
@Data
public class JwtUtil {
    private String key;
    private long ttl;

    //1.创建jwt得到token字符串(jwt的id，主题部分，声明携带的参数)
    public String getToken(String id,String subject,String roles ){
        //1.得到当前时间的毫秒数
        long l = System.currentTimeMillis();
        //2.创建一个jwtbuilder对象
        JwtBuilder jwtBuilder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(new Date())
                .claim("roles", roles)
                .signWith(SignatureAlgorithm.HS256, key);
        //3.判断时间是否存在
        if(ttl>0){
            jwtBuilder.setExpiration(new Date(l+ttl));
        }
        //4.返回token字符串
        return jwtBuilder.compact();
    }

    //2.解析token字符串
    public Claims parseToken(String token){
        //1.根据调用jwts静态方法进行解析
        Claims body = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();
        //2.返回
        return body;
    }

}
